package com.example.liuke.guangguang;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.MediaStore.Images.Thumbnails;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.liuke.guangguang.adapter.ApplistAdapter;
import com.example.liuke.guangguang.base.baseactivity;
import com.example.liuke.guangguang.base.mybaseapplication;
import com.example.liuke.guangguang.bean.AppInfo;
import com.example.liuke.guangguang.bean.mseeagebean;
import com.example.liuke.guangguang.dialog.MProgressDialog;
import com.example.liuke.guangguang.myweidgt.FloatWindowService;
import com.example.liuke.guangguang.timertask.MyTask;
import com.example.liuke.guangguang.timertask.TimeHandler;
import com.example.liuke.guangguang.timertask.TimeTask;
import com.example.liuke.guangguang.ui.BookActivity;
import com.example.liuke.guangguang.ui.ChartsoneActivity;
import com.example.liuke.guangguang.ui.EventbusActivity;
import com.example.liuke.guangguang.ui.ExeclActivity;
import com.example.liuke.guangguang.ui.GifActivity;
import com.example.liuke.guangguang.ui.GreenDaoActivity;
import com.example.liuke.guangguang.ui.IMEActivity;
import com.example.liuke.guangguang.ui.KerkeeActivity;
import com.example.liuke.guangguang.ui.MapActivity;
import com.example.liuke.guangguang.ui.NativeJsActivity;
import com.example.liuke.guangguang.ui.RecyActivity;
import com.example.liuke.guangguang.ui.UsbActivity;
import com.example.liuke.guangguang.ui.VideopicActivity;
import com.example.liuke.guangguang.ui.Videotwo;
import com.example.liuke.guangguang.ui.Webview_JS_Activity;
import com.example.liuke.guangguang.ui.effectsActivity;
import com.example.liuke.guangguang.ui.timeActivity;
import com.example.liuke.guangguang.untils.DateUntils;
import com.example.liuke.guangguang.untils.Getfiles;
import com.example.liuke.guangguang.untils.ZipUtil;
import com.example.liuke.guangguang.untils.fileuntils;
import com.example.liuke.guangguang.untils.netuntils;
import com.example.liuke.guangguang.untils.openapp;
import com.example.liuke.guangguang.untils.xmlcomparison;
import com.tuyenmonkey.mkloader.MKLoader;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.ui.ViewInject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import javax.xml.parsers.SAXParserFactory;

import ezy.assist.compat.SettingsCompat;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.grantland.widget.AutofitTextView;

import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends baseactivity implements View.OnClickListener {
    // 要申请的权限
    private String[] permissions = {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"};
    private AlertDialog dialog;
    private Button jiexi, guoguangmp4, web, button3, button4, button5, button, button2jian,
            eventbus, button6, button8, button9, button10, button12, button15, button16, button18,
            button19, button7, button20, addlayout, dbbutton, effectsbutton, uuid, bookcase, chart1, settext,
            ime, buttonGif, buttonDialog, copy, unzip, net;
    private AutofitTextView autotext;
    private EditText autoed;
    private URL url = null;
    private StringBuffer sb = new StringBuffer();
    private String line = null;
    private BufferedReader buffer = null;
    private String ascontent = "1";
    private ArrayList<String> Content = new ArrayList<String>();
    private String[] picture, piv;
    private NoScrollGridView noScrollGridView;
    // 请求对象
    public static KJHttp http;
    public static HttpConfig httpconfig;
    private ProgressBar myprgressBar;
    private ImageView myim;
    private AudioManager mAudioManager;
    public static ArrayList<String> Urls = new ArrayList<>();
    //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)  
    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;
    private MProgressDialog mMProgressDialog;
    private List<HashMap<String, String>> hashMapListload = new ArrayList<>();
    private List<HashMap<String, String>> hashMapListdel = new ArrayList<>();
    private String version = "";
    private List<HashMap<String, String>> hashMapListtemp = new ArrayList<>();
    private String nodename;
    private HashMap<String, String> hashMap;
    private List<String> urllist = new ArrayList<>();
    private String ip = "www";
    private String codeno = "wwww";
    private String shebeiip = "";//file://
    //mybaseapplication.getContextObject().getFilesDir().getAbsolutePath() + File.separator
    private String config_savepath = "/mnt/sda/sda1/ggagent/";
    private String filename = "/mnt/sda/sda1/ggagent/agentconfig.txt";
    public static final String ACTION_REBOOT =
            "android.intent.action.REBOOT";
    public static final String ACTION_REQUEST_SHUTDOWN = "android.intent.action.ACTION_REQUEST_SHUTDOWN";
    private Socket socket;
    private Handler handler1 = new Handler();
    private String orderTime = "07:00:00";
    private Handler handler = new Handler();
    private Handler handler2 = new Handler();
    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            VideoDownloadAPI("http://tb-video.bdstatic.com/tieba-smallvideo-transcode/37718689_49e111ffc72749735384857a2d464846_d0e9f9fbafe0_2.mp4", myprgressBar);
        }
    };
    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            if (null != http) {
                http.cancelAll();
                handler2.postDelayed(runnable2, 3000);//延时时间，达到限制带宽的假象。
            }
            //VideoDownloadAPI("http://tb-video.bdstatic.com/tieba-smallvideo-transcode/37718689_49e111ffc72749735384857a2d464846_d0e9f9fbafe0_2.mp4", myprgressBar);
        }
    };
    TimeHandler<MyTask> timeHandler = new TimeHandler<MyTask>() {
        @Override
        public void exeTask(MyTask mTasks) {
            //准时执行
            System.out.println(mTasks.name);
        }

        @Override
        public void overdueTask(MyTask mTask) {
            ///已过期的任务
        }

        @Override
        public void futureTask(MyTask mTask) {
            //未来将要执行的任务
        }
    };

    private GridLayoutManager gridLayoutManager;
    private List<AppInfo> mlistAppInfo = new ArrayList<>();
    private ApplistAdapter applistAdapter;
    private PackageManager pm;
    public static final int FILTER_ALL_APP = 0;
    public static final int FILTER_SYSTEM_APP = 1;
    public static final int FILTER_THIRD_APP = 2;
    public static final int FILTER_SDCARD_APP = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        initnet();


        TimeTask<MyTask> myTaskTimeTask = new TimeTask<>(MainActivity.this, "1"); // 创建一个任务处理器
        myTaskTimeTask.addHandler(timeHandler); //添加时间回掉
        myTaskTimeTask.setTasks(creatTasks());//创建时间任务资源 把资源放进去处理
        myTaskTimeTask.startLooperTask();//  启动

        if (!netuntils.isNetworkConnected(this)) {
            netuntils.no_net_action(this);
        }

        ViewInject.toast(this, DateUntils.getCurrentDateHHMMSS() + "   /  " + orderTime.substring(0, orderTime.lastIndexOf(":")));
        //conn();
        Intent intent = new Intent();
        intent.setAction("android.intent.action.ACTION_SHUTDOWN");
        PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        // pManager.reboot(null);//重启</span>
        // shutdown();
        try {

            //获得ServiceManager类
            Class<?> ServiceManager = Class.forName("android.os.ServiceManager");

            //获得ServiceManager的getService方法
            Method getService = ServiceManager.getMethod("getService", java.lang.String.class);

            //调用getService获取RemoteService
            Object oRemoteService = getService.invoke(null, Context.POWER_SERVICE);

            //获得IPowerManager.Stub类
            Class<?> cStub = Class.forName("android.os.IPowerManager$Stub");
            //获得asInterface方法
            Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
            //调用asInterface方法获取IPowerManager对象
            Object oIPowerManager = asInterface.invoke(null, oRemoteService);
            //获得shutdown()方法
            Method shutdown = oIPowerManager.getClass().getMethod("shutdown", boolean.class, boolean.class);
            //调用shutdown()方法
            shutdown.invoke(oIPowerManager, false, true);

        } catch (Exception e) {

        }

        //startActivity(intent);
        //sendBroadcast(intent);
        // 版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                showDialogTipUserRequestPermission();
            }
        }
        ActivityCompat.requestPermissions(this, permissions, 321);
        Toast.makeText(this, getExternalStorageDirectory().toString() + "\n" + mybaseapplication.getContextObject().getFilesDir().getAbsolutePath(), Toast.LENGTH_SHORT).show();
        System.out.println("guoguanglog: " + mybaseapplication.getContextObject().getFilesDir().getAbsolutePath() + "\n" + getExternalStorageDirectory().toString());
        urllist = fileuntils.getImagePathFromSD("ggplayResourse/picture");
        fileuntils.writeStringToFile(ip + ";" + codeno, config_savepath, filename, false);
        //String string = fileuntils.readFile(AppConfig.ggagent_jsonsavepath);
        jiexi = (Button) findViewById(R.id.guoguangmp4);
        guoguangmp4 = (Button) findViewById(R.id.guoguang1);
        web = (Button) findViewById(R.id.web);
        effectsbutton = (Button) findViewById(R.id.effectsbutton);
        button3 = (Button) findViewById(R.id.button3);
        button4 = (Button) findViewById(R.id.button4);
        button5 = (Button) findViewById(R.id.button5);
        button = (Button) findViewById(R.id.button);
        eventbus = (Button) findViewById(R.id.eventbus);
        button6 = (Button) findViewById(R.id.button6);
        button8 = (Button) findViewById(R.id.button8);
        button9 = (Button) findViewById(R.id.button9);
        button10 = (Button) findViewById(R.id.button10);
        button12 = (Button) findViewById(R.id.button12);
        button15 = (Button) findViewById(R.id.button15);
        button16 = (Button) findViewById(R.id.button16);
        button18 = (Button) findViewById(R.id.button18);
        button19 = (Button) findViewById(R.id.button19);
        button7 = (Button) findViewById(R.id.button7);
        button20 = (Button) findViewById(R.id.button20);
        addlayout = (Button) findViewById(R.id.addlayout);
        dbbutton = (Button) findViewById(R.id.dbbutton);
        button2jian = (Button) findViewById(R.id.button2jian);
        ime = (Button) findViewById(R.id.ime);
        buttonGif = (Button) findViewById(R.id.buttonGif);
        buttonDialog = (Button) findViewById(R.id.buttonDialog);
        copy = (Button) findViewById(R.id.copy);
        unzip = (Button) findViewById(R.id.unzip);
        net = (Button) findViewById(R.id.net);
        net.setOnClickListener(this);
        unzip.setOnClickListener(this);
        copy.setOnClickListener(this);
        buttonDialog.setOnClickListener(this);
        buttonGif.setOnClickListener(this);
        noScrollGridView = (NoScrollGridView) findViewById(R.id.gridview);
        myprgressBar = (ProgressBar) findViewById(R.id.myprogress);
        myim = (ImageView) findViewById(R.id.mp4);
        uuid = (Button) findViewById(R.id.uuid);
        bookcase = (Button) findViewById(R.id.bookcase);
        chart1 = (Button) findViewById(R.id.chart1);
        ime.setOnClickListener(this);
        chart1.setOnClickListener(this);
        bookcase.setOnClickListener(this);
        jiexi.setOnClickListener(this);
        guoguangmp4.setOnClickListener(this);
        web.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        button5.setOnClickListener(this);
        button.setOnClickListener(this);
        button2jian.setOnClickListener(this);
        eventbus.setOnClickListener(this);
        button6.setOnClickListener(this);
        button8.setOnClickListener(this);
        button9.setOnClickListener(this);
        button10.setOnClickListener(this);
        button12.setOnClickListener(this);
        button15.setOnClickListener(this);
        button16.setOnClickListener(this);
        button18.setOnClickListener(this);
        button19.setOnClickListener(this);
        button7.setOnClickListener(this);
        button20.setOnClickListener(this);
        addlayout.setOnClickListener(this);
        dbbutton.setOnClickListener(this);
        effectsbutton.setOnClickListener(this);
        uuid.setOnClickListener(this);
        autotext = (AutofitTextView) findViewById(R.id.autotext);
        autoed = (EditText) findViewById(R.id.autoed);
        settext = (Button) findViewById(R.id.settext);
        settext.setOnClickListener(this);
        String s = fileuntils.getFileName("/mnt/sda/sda1/ggagent/agentconfig.txt");
        String s1 = fileuntils.getFileNameNE("/mnt/sda/sda1/ggagent/agentconfig.txt");
        String path = getExternalStorageDirectory().toString() + File.separator
                + "LDTeaTableAppResourse/户籍";
        List<String> list = fileuntils.getFilesAllName(path);
       /* for (String s2 : list) {
            System.out.println("文件夹名为：" + fileuntils.getFileName(s2));
        }*/
        System.out.println("文件名：" + s + " // " + s1);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        try {
            version = getVersionName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        a();
        getpermission();
    }

    private void getpermission() {
        //华为的5.0系统居然也有这个权限，而且华为5.0还没有这个权限的设置界面，它是另外一个程序控制的，不然会报activitynotfound异常
        //小米和魅族也不一样，公司的阉割系统更是千奇百怪，无法搞。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                SettingsCompat.manageDrawOverlays(this);
            } else {
                Intent intent = new Intent(this, FloatWindowService.class);
                startService(intent);
            }
        } else {
            Intent intent = new Intent(this, FloatWindowService.class);
            startService(intent);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    private List<MyTask> creatTasks() {
        return new ArrayList<MyTask>() {{
            MyTask BobTask = new MyTask();
            //******测试demo请务必修改时间******
            BobTask.setStarTime(dataOne("2018-09-14 10:16:00"));   //当前时间
            BobTask.setEndTime(dataOne("2018-09-14 10:16:05"));  //5秒后结束
            BobTask.name = "Bob";
            add(BobTask);

            MyTask benTask = new MyTask();
            benTask.setStarTime(dataOne("2018-09-14 10:16:10")); //10秒开始
            benTask.setEndTime(dataOne("2018-09-14 10:16:15")); //15秒后结束
            benTask.name = "Ben";
            add(benTask);
        }};
    }

    public static long dataOne(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date;
        String times = null;
        try {
            date = sdr.parse(time);
            long l = date.getTime();
            String stf = String.valueOf(l);
            times = stf.substring(0, 10);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Long.parseLong(times) * 1000;

    }

    /**
     * 建立服务端连接
     */
    public void conn() {
        new Thread() {

            @Override
            public void run() {
                try {
                    socket = new Socket("172.20.10.4", 9999);
                    Log.e("JAVA", "建立连接：" + socket);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 发送消息
     */
    public void send() {
        new Thread() {
            @Override
            public void run() {
                try {
                    // socket.getInputStream()
                    DataOutputStream writer = new DataOutputStream(socket.getOutputStream());
                    writer.writeUTF("嘿嘿，你好啊，服务器.."); // 写一个UTF-8的信息

                    System.out.println("发送消息");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static int shutdown() {
        int r = 0;
        try {
            Process process = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});
            r = process.waitFor();
            java.lang.System.out.println("r:" + r);
        } catch (IOException e) {
            e.printStackTrace();
            r = -1;
        } catch (InterruptedException e) {
            e.printStackTrace();
            r = -1;
        }
        return r;
    }

    // 提示用户该请求权限的弹出框
    private void showDialogTipUserRequestPermission() {

        new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("由于应用需要获取存储空间；\n否则，您将无法正常使用！")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startRequestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 开始提交请求权限
    private void startRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    // 用户权限 申请 的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 321) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    boolean b = shouldShowRequestPermissionRationale(permissions[0]);
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                        showDialogTipUserGoToAppSettting();
                    } else
                        finish();
                } else {
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSettting() {
        dialog = new AlertDialog.Builder(this)
                .setTitle("存储权限不可用")
                .setMessage("请在-应用设置-权限-中，允许支付宝使用存储权限来保存用户数据")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {

            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(this, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                    showDialogTipUserGoToAppSettting();
                } else {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    Toast.makeText(this, "权限获取成功", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void a() {
        List<String> list = new ArrayList<>();
        list.add("a1");
        list.add("a2");
        list.add("a3");
        list.add("a4");
        list.add("a5");
        list.add("a6");
        Observable.just(list).flatMap(new Function<List<String>, ObservableSource<?>>() {
            @Override
            public ObservableSource<?> apply(List<String> strings) throws Exception {
                return Observable.fromIterable(strings);
            }
        }).take(5).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object s) throws Exception {
                System.out.println("rxjava的测试：" + s);
            }
        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //继承了Activity的onTouchEvent方法，直接监听点击事件  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            //当手指按下的时候  
            x1 = event.getX();
            y1 = event.getY();
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            //当手指离开的时候  
            x2 = event.getX();
            y2 = event.getY();
            if (y1 - y2 > 50) {
                mseeagebean mseeagebean = new mseeagebean();
                mseeagebean.setString("sa");
                EventBus.getDefault().post(mseeagebean);
                Toast.makeText(MainActivity.this, "向上滑" + "时间：" + time(), Toast.LENGTH_SHORT).show();
            } else if (y2 - y1 > 50) {
                Toast.makeText(MainActivity.this, "向下滑+ip: " + getIPAddress(this), Toast.LENGTH_SHORT).show();
            } else if (x1 - x2 > 50) {
                Toast.makeText(MainActivity.this, "向左滑+/获取后缀名" + Getfiles.getFileName("adc/ad.jpg"), Toast.LENGTH_SHORT).show();
            } else if (x2 - x1 > 50) {
                Toast.makeText(MainActivity.this, "向右滑+/获取版本信息：" + version + File.separator, Toast.LENGTH_SHORT).show();
            }
        }
        return super.onTouchEvent(event);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.guoguang1:
                Content.clear();
                int randomcode = (int) (Math.random() * 10000 + 1);//这是必须要加的，防止缓存，url为空
                // download("http://106.14.253.228:8080/Update.xml");   http://106.14.253.228:8080/Update.xml
                mytask my = new mytask();//http://192.168.15.203:8180/ibms/resource/xmlAndZip/13_SDJNLX01002_20180125082301618/Update.xml
                my.execute("http://192.168.15.203:8180/ibms/resource/xmlAndZip/13_SDJNLX01002_20180125082301618/Update.xml" + "?" + "randomcode=" + randomcode);
                //http://192.168.15.203:8180/ibms/resource/xmlAndZip/13_SDJNLX01002_20180125082301618/Update.xml?randomcode=6658

                if (!ascontent.equals("")) {
                    try {
                        // 创建一个SAXParserFactory
                        SAXParserFactory factory = SAXParserFactory.newInstance();
                        XMLReader reader = factory.newSAXParser().getXMLReader();
                        // 为XMLReader设置内容处理器
                        reader.setContentHandler(new Myhandler(Content));
                        // 开始解析文件
                        reader.parse(new InputSource(new StringReader(ascontent)));

                        //InputStream inputStream = getResources().getAssets().open("g.xml");

                        //InputSource inputSource = new InputSource(inputStream);
                        //reader.parse(inputSource);
                        System.out.println("shuxiqang" + Content.size());
                        picture = split(Content.get(0));

                        if (Content != null && Content.size() != 0) {

                            for (int i = 0; i < Content.size(); i++) {//判断有几个节点
                                System.out.println("Content.size()" + "  / " + Content.get(i).toString());
                                if (i == 0) {
                                    picture = split(Content.get(i));
                                }

                                for (int j = 0; j < picture.length; j++) {
                                    Urls.add("http://" + picture[j]);
                                    System.out.println("shuxiqangsize" + picture[j]);
                                }
                            }
                        }

                        Toast.makeText(this, Content.get(1), Toast.LENGTH_LONG).show();
                        ArrayList<String> imageUrls = new ArrayList<>();
                        System.out.println("sizeasasasasasa" + picture.length + picture[0]);
                        imageUrls.add("http://106.14.253.228:8080" + picture[0]);
                        imageUrls.add("http://106.14.253.228:8080" + picture[1]);
                        imageUrls.add("http://106.14.253.228:8080" + picture[2]);
                        noScrollGridView.setAdapter(new NoScrollGridAdapter(this, imageUrls));
                    } catch (Exception e) {
                        System.out.println("shuxiqangsizeccccc");
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(this, "下载中...", Toast.LENGTH_SHORT).show();
                }
                if (null != picture && picture.length != 0) {

                }

                break;
            //http://tb-video.bdstatic.com/tieba-smallvideo-transcode/37718689_49e111ffc72749735384857a2d464846_d0e9f9fbafe0_2.mp4
            case R.id.guoguangmp4:// http://106.14.253.228:8080/smarterbanking/resource/video/%E5%BE%AE%E5%95%86%E5%9F%8E.mp4
                //handler.postDelayed(runnable1, 1000);
                VideoDownloadAPI("http://tb-video.bdstatic.com/tieba-smallvideo-transcode/37718689_49e111ffc72749735384857a2d464846_d0e9f9fbafe0_2.mp4", myprgressBar);
                // download(myprgressBar, "http://tb-video.bdstatic.com/tieba-smallvideo-transcode/37718689_49e111ffc72749735384857a2d464846_d0e9f9fbafe0_2.mp4");
                /*if (Content.isEmpty()) {
                    Toast.makeText(this, "请先解析", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, Content.get(1), Toast.LENGTH_SHORT).show();
                    // http://221.228.226.23/6/w/o/b/w/wobwgoaupdyhvuannrgukoojttuugh/he.yinyuetai.com/DD5201536EDB9652BC457D277E27123B.flv
                    // VideoDownloadAPI("http://106.14.253.228:8080/smarterbanking/resource/video/%E5%BE%AE%E5%95%86%E5%9F%8E.mp4",
                    // myprgressBar);
                    // VideoDownloadAPI("http://106.14.253.228:8080/smarterbanking/resource/video/微商城.mp4",
                    // myprgressBar);
                    VideoDownloadAPI(
                            "http://221.228.226.23/6/w/o/b/w/wobwgoaupdyhvuannrgukoojttuugh/he.yinyuetai.com/DD5201536EDB9652BC457D277E27123B.flv",
                            myprgressBar);
                }
*/
                break;
            case R.id.web:
                startActivity(new Intent(this, Webview_JS_Activity.class));
                Toast.makeText(this, "请先解析", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button3:
                startActivity(new Intent(this, NativeJsActivity.class));
                break;
            case R.id.button4:
                startActivity(new Intent(this, VideopicActivity.class));
                break;
            case R.id.button5:
                startActivity(new Intent(this, Videotwo.class));
                break;
            case R.id.button:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
                break;
            case R.id.button2jian:
                mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
                break;
            case R.id.eventbus:
                startActivity(new Intent(this, EventbusActivity.class));
                break;
            case R.id.button6://重启按钮测试不行，现在测试dom4j解析xml
                System.out.println("women shiyige dadadad");
                //reboot();//重启好像不行
                Toast.makeText(this, "dom4j解析测试", Toast.LENGTH_SHORT).show();
                hashMapListtemp.clear();
                dom4jxml();
                System.out.println("测试数据size：" + hashMapListtemp.size());
                for (HashMap<String, String> hashMap : hashMapListtemp) {
                    System.out.println("测试数据：" + hashMap.get("resourceName") + "&" + hashMap.get("path") + "&" + hashMap.get("URL"));
                }
                break;
            case R.id.button7://xml比对
                String xmlurl1 = getExternalStorageDirectory().toString() + File.separator + "bankpic/Update.xml";
                String xmlurl2 = getExternalStorageDirectory().toString() + File.separator + "bankpic/Update2.xml";


                //xmlcomparison myxmlcomparison = new xmlcomparison(xmlurl1,xmlurl2);


                xmlcomparison xmlcomparison = new xmlcomparison(getExternalStorageDirectory().toString() + File.separator + "ResourcesDownload/Update.xml",
                        getExternalStorageDirectory().toString() + File.separator + "ResourcesDownload/newxml/Update.xml");
                hashMapListload = xmlcomparison.GetDownloadList();
                hashMapListdel = xmlcomparison.GetDeleteList();


                //hashMapListload=myxmlcomparison.GetDownloadList();
                System.out.println("hashMapListloadsize:" + hashMapListload.size());
                for (HashMap<String, String> hashMap : hashMapListload) {
                    System.out.println("hashMapListload的下载存储地址: " + hashMap.get("path"));
                    System.out.println("hashMapListload的下载url值: " + hashMap.get("URL"));
                }

                /*hashMapListdel=myxmlcomparison.GetDeleteList();
                System.out.println("hashMapListloadsize:" + hashMapListdel.size());
                for (HashMap<String,String> hashMap: hashMapListdel){
                    System.out.println("hashMapListdel的下载存储地址: "+hashMap.get("path"));
                    System.out.println("hashMapListdel的下载url值: "+hashMap.get("URL"));
                }*/

                String a = "/smarterbanking/resource/imgs/20170706190819039/ad1.jpg;/smarterbanking/resource/imgs/20170706190819130/ad2.jpg;/smarterbanking/resource/imgs/20170706190819130/ad3.jpg";
                String b = "/smarterbanking/resource/imgs/20170706190819130/ad3.jpg";
                System.out.println(".....aaa" + a.contains(b));
                break;
            case R.id.button8:
                startActivity(new Intent(this, UsbActivity.class));
                break;
            case R.id.button9://屏幕翻转
                System.out.println("屏幕方向：" + getRequestedOrientation());
                //横屏正方向
                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {//0
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
                }
                //横屏反方向
                else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {//8
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
                //纵屏正方向
                else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {//1
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                }
                //纵屏反方向
                else if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {//9
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                break;
            case R.id.button10:
                startActivity(new Intent(this, MapActivity.class));
                break;
            case R.id.button12:


                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        send();
                        //System.out.println("log   " + "后台服务启动");
                        //handler1.postDelayed(this, 5000);
                    }
                };
                handler1.postDelayed(runnable, 5000);

                //showProgressDialog01();
                break;
            case R.id.button15:
                button15.setText(getCurrentTime_Today());
                break;
            case R.id.button16:
                startActivity(new Intent(this, ExeclActivity.class));
                break;
            case R.id.button18:
                startActivity(new Intent(this, timeActivity.class));
                break;
            case R.id.button19:
                startActivity(new Intent(this, KerkeeActivity.class));
                break;
            case R.id.button20:
                startActivity(new Intent(this, RecyActivity.class));
                break;
            case R.id.addlayout:
                //startActivity(new Intent(this, DongtaiAddViewActivity.class));
                long kj = calculateLength("asas卡是捷克");
                System.out.println(kj);
                String kk = "sss手机卡";
                try {
                    kk = new String(kk.getBytes("UTF-8"), "GB2312");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.dbbutton:
                startActivity(new Intent(this, GreenDaoActivity.class));
                break;
            case R.id.effectsbutton:
                startActivity(new Intent(this, effectsActivity.class));
                break;
            case R.id.uuid:
                //IMEI（imei）
                TelephonyManager tm = (TelephonyManager) mybaseapplication.getContextObject().getSystemService(Context.TELEPHONY_SERVICE);
                String imei = tm.getDeviceId();
                if (!TextUtils.isEmpty(imei)) {
                    //Toast.makeText(this,imei+"",Toast.LENGTH_SHORT).show();
                }

//序列号（sn）
                /*String sn = tm.getSimSerialNumber();
                if(!TextUtils.isEmpty(sn)){
                    deviceId.append("sn");
                    deviceId.append(sn);
                    return deviceId.toString();
                }*/


                Toast.makeText(this, getMyUUID() + "\nimei: " + tm.getDeviceId() + "\n序列号：" + Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID), Toast.LENGTH_SHORT).show();
                break;
            case R.id.bookcase:
                startActivity(new Intent(this, BookActivity.class));
                break;
            case R.id.chart1:
                startActivity(new Intent(this, ChartsoneActivity.class));
                break;
            case R.id.settext:
                autotext.setText(autoed.getText().toString());
                break;
            case R.id.ime:
                startActivity(new Intent(this, IMEActivity.class));
                break;
            case R.id.buttonGif:
                startActivity(new Intent(this, GifActivity.class));
                break;
            case R.id.buttonDialog:
                final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
                //填充对话框的布局
                View nflate = LayoutInflater.from(this).inflate(R.layout.dialogapp, null);
                //setCancelable(iscancelable);//点击外部不可dismiss
                //setCanceledOnTouchOutside(isBackCanCelable);
                //初始化控件
                final RecyclerView r = (RecyclerView) nflate.findViewById(R.id.applist);
                final MKLoader m = (MKLoader) nflate.findViewById(R.id.mk);
                //queryAppInfo();
                mlistAppInfo.clear();
                //将布局设置给Dialog
                dialog.setContentView(nflate);
                //获取当前Activity所在的窗体
                Window dialogWindow = dialog.getWindow();
                //设置Dialog从窗体底部弹出
                dialogWindow.setGravity(Gravity.BOTTOM);
                dialogWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                //获得窗体的属性
                WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                //如果没有这行代码，弹框的内容会自适应，而不会充满父控件
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.y = 40;//设置Dialog距离底部的距离
                //将属性设置给窗体
                dialogWindow.setAttributes(lp);
                dialog.show();
                m.setVisibility(View.VISIBLE);
                r.setVisibility(View.INVISIBLE);
                Observable.create(new ObservableOnSubscribe<Integer>() {

                    @Override
                    public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                        mlistAppInfo = queryFilterAppInfo(FILTER_THIRD_APP);
                        emitter.onNext(1);
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Integer>() {
                            @Override
                            public void accept(Integer integer) throws Exception {
                                Log.d("所在的线程：", Thread.currentThread().getName());
                                Log.d("接收到的数据:", "integer:" + integer);
                                m.setVisibility(View.INVISIBLE);
                                r.setVisibility(View.VISIBLE);
                                applistAdapter = new ApplistAdapter(MainActivity.this, R.layout.appitemlayout, mlistAppInfo);
                                gridLayoutManager = new GridLayoutManager(MainActivity.this, 5);
                                applistAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        Toast.makeText(MainActivity.this, "onItemClick" + position, Toast.LENGTH_SHORT).show();
                                        if (dialog.isShowing()) {
                                            dialog.dismiss();
                                        }
                                        openapp.startActivityForPackage(MainActivity.this, mlistAppInfo.get(position).getPkgName());
                                    }
                                });
                                r.setLayoutManager(gridLayoutManager);
                                r.setItemAnimator(new DefaultItemAnimator());
                                r.setAdapter(applistAdapter);
                            }
                        });
                break;
            case R.id.copy:
                final Dialog dialogcopy = new Dialog(this, R.style.ActionSheetDialogStyle);
                //填充对话框的布局
                View nflate1 = LayoutInflater.from(this).inflate(R.layout.dialogcopy, null);
                //setCancelable(iscancelable);//点击外部不可dismiss
                //setCanceledOnTouchOutside(isBackCanCelable);
                //初始化控件
                final TextView t = (TextView) nflate1.findViewById(R.id.copytext);
                t.setText("资源复制中请稍后......");
                //queryAppInfo();
                mlistAppInfo.clear();
                //将布局设置给Dialog
                dialogcopy.setContentView(nflate1);
                dialogcopy.show();
                final String filefolderpath = Environment.getExternalStorageDirectory().toString() + File.separator + "LDTeaTableAppResourse";
                final String filefolderpath2 = Environment.getExternalStorageDirectory().toString() + File.separator + "aa/aa";
                Observable.create(new ObservableOnSubscribe<Integer>() {

                    @Override
                    public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                        fileuntils.copyFolder(filefolderpath, filefolderpath2);
                        emitter.onNext(1);
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Integer>() {
                            @Override
                            public void accept(Integer integer) throws Exception {
                                Log.d("所在的线程：", Thread.currentThread().getName());
                                Log.d("接收到的数据:", "integer:" + integer);
                                t.setText("复制完成");
                                if (dialogcopy.isShowing()) {
                                    dialogcopy.dismiss();
                                }
                            }
                        });
                break;
            case R.id.unzip:
                final Dialog dialogcopy1 = new Dialog(this, R.style.ActionSheetDialogStyle);
                //填充对话框的布局
                View nflate11 = LayoutInflater.from(this).inflate(R.layout.dialogcopy, null);
                //setCancelable(iscancelable);//点击外部不可dismiss
                //setCanceledOnTouchOutside(isBackCanCelable);
                //初始化控件
                final TextView t1 = (TextView) nflate11.findViewById(R.id.copytext);
                t1.setText("解压中......");
                //queryAppInfo();
                mlistAppInfo.clear();
                //将布局设置给Dialog
                dialogcopy1.setContentView(nflate11);
                dialogcopy1.show();
                Observable.create(new ObservableOnSubscribe<Integer>() {

                    @Override
                    public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
                        String zipfilepath = Environment.getExternalStorageDirectory().toString() + File.separator + "aa/programResource.zip";
                        String aimDir = Environment.getExternalStorageDirectory().toString() + File.separator + "aa/bbbb";
                        ZipUtil.decompress(zipfilepath, aimDir, false);
                        emitter.onNext(1);
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Integer>() {
                            @Override
                            public void accept(Integer integer) throws Exception {
                                Log.d("所在的线程：", Thread.currentThread().getName());
                                Log.d("接收到的数据:", "integer:" + integer);
                                t1.setText("解压完成");
                                if (dialogcopy1.isShowing()) {
                                    dialogcopy1.dismiss();
                                }
                            }
                        });
                break;
            case R.id.net:
                Toast.makeText(this, "网络是否连接："+isConnected()+"   网络是否可用"+ isAvailable(), Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    /**
     * 网络是否连接
     *
     * @return
     */
    public static boolean isConnected() {
        NetworkInfo info = getNetworkInfo();
        return info != null && info.isConnected();
    }

    /**
     * 获取活动网络信息
     *
     * @return NetworkInfo
     */
    public static NetworkInfo getNetworkInfo() {
        ConnectivityManager cm = (ConnectivityManager) mybaseapplication.getContextObject().getSystemService(Context.CONNECTIVITY_SERVICE);

        return cm.getActiveNetworkInfo();
    }


    /**
     * 网络是否可用
     *
     * @return
     */
    public static boolean isAvailable() {
        NetworkInfo info = getNetworkInfo();
        return info != null && info.isAvailable();
    }

    // 根据查询条件，查询特定的ApplicationInfo
    private List<AppInfo> queryFilterAppInfo(int filter) {
        pm = this.getPackageManager();
        // 查询所有已经安装的应用程序
        List<ApplicationInfo> listAppcations = pm
                .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(listAppcations,
                new ApplicationInfo.DisplayNameComparator(pm));// 排序
        List<AppInfo> appInfos = new ArrayList<>(); // 保存过滤查到的AppInfo
        // 根据条件来过滤
        switch (filter) {
            case FILTER_ALL_APP: //  所有应用程序
                appInfos.clear();
                for (ApplicationInfo app : listAppcations) {
                    appInfos.add(getAppInfo(app));
                }
                return appInfos;
            case FILTER_SYSTEM_APP: // 系统程序
                appInfos.clear();
                for (ApplicationInfo app : listAppcations) {
                    if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                        appInfos.add(getAppInfo(app));
                    }
                }
                return appInfos;
            case FILTER_THIRD_APP: // 第三方app
                appInfos.clear();
                for (ApplicationInfo app : listAppcations) {
                    if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                        appInfos.add(getAppInfo(app));
                    }
                }
                break;
            case FILTER_SDCARD_APP: //  安装在SDCard的应用程序
                appInfos.clear();
                for (ApplicationInfo app : listAppcations) {
                    if ((app.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
                        appInfos.add(getAppInfo(app));
                    }
                }
                return appInfos;
            default:
                return null;
        }
        return appInfos;
    }

    // 构造一个AppInfo对象 ，并赋值 ֵ
    private AppInfo getAppInfo(ApplicationInfo app) {
        AppInfo appInfo = new AppInfo();
        appInfo.setAppLabel((String) app.loadLabel(pm));
        appInfo.setAppIcon(app.loadIcon(pm));
        appInfo.setPkgName(app.packageName);
        return appInfo;
    }

    public void queryAppInfo() {
        PackageManager pm = this.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfos = pm
                .queryIntentActivities(mainIntent, PackageManager.MATCH_DEFAULT_ONLY);
        Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
        if (mlistAppInfo != null) {
            mlistAppInfo.clear();
            for (ResolveInfo reInfo : resolveInfos) {
                String activityName = reInfo.activityInfo.name;
                String pkgName = reInfo.activityInfo.packageName;
                String appLabel = (String) reInfo.loadLabel(pm);
                Drawable icon = reInfo.loadIcon(pm);
                Intent launchIntent = new Intent();
                launchIntent.setComponent(new ComponentName(pkgName,
                        activityName));
                AppInfo appInfo = new AppInfo();
                appInfo.setAppLabel(appLabel);
                appInfo.setPkgName(pkgName);
                appInfo.setAppIcon(icon);
                appInfo.setIntent(launchIntent);
                mlistAppInfo.add(appInfo);
            }
        }
    }


    /**
     * 计算lklk分享内容的字数，一个汉字=两个英文字母，一个中文标点=两个英文标点 注意：该函数的不适用于对单个字符进行计算，因为单个字符四舍五入后都是1
     *
     * @param c
     * @return
     */
    public static long calculateLength(CharSequence c) {
        double len = 0;
        for (int i = 0; i < c.length(); i++) {
            int tmp = (int) c.charAt(i);
            if (tmp > 0 && tmp < 127) {
                len += 0.5;
            } else {
                len++;
            }
        }
        return Math.round(len);
    }

    private String getVersionName() throws Exception {
        PackageManager packageManager = getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    //读取XML文件获取Document对象
    //读取XML文本内容获取Document对象
    private void dom4jxml() {
        String xmlurl = getExternalStorageDirectory().toString() + File.separator + "bankpic/update.xml";
        Document document;
        //创建SAXReader对象  
        SAXReader reader = new SAXReader();
        //读取文件 转换成Document  
        try {
            document = reader.read(new File(xmlurl));
            //获取根节点元素对象  
            Element root = document.getRootElement();
            //遍历  
            listnodes(root);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //遍历当前节点下的所有子节点
    public void listnodes(Element node) {
        System.out.println("dom4jxml当前子节点的名称：" + node.getName());
        //首先获取当前子节点的所有属性节点
        List<Attribute> list = node.attributes();
        //遍历属性节点
        for (Attribute attribute : list) {
            System.out.println("dom4jxml属性:" + attribute.getName() + ":" + attribute.getValue());
        }
        //如果当前节点内容不为空则输出
        if (!(node.getTextTrim().equals(""))) {
            System.out.println("dom4jxml" + node.getName() + ":" + node.getText());
        }


        if (node.getName().equals("node") || node.getName().equals("root")) {//
            //hashMap = new HashMap<>();
            List<Attribute> list1 = node.attributes();
            for (Attribute attribute : list1) {
                if (attribute.getName().equals("name")) {
                    //hashMap.put("resourceName", attribute.getValue());
                    nodename = attribute.getValue();
                }
            }
        }
        if (node.getName().equals("protype")) {
            hashMap = new HashMap<>();
            hashMap.put("resourceName", nodename);
        } else if (node.getName().equals("path")) {
            System.out.println("dom4jxml" + node.getName() + ":" + node.getText());
            hashMap.put("path", node.getText());//保存路径  是否现在将下载路径分割开来  这是一种做法 ，还有一种做法就是先保存，之后比对的时候在分割比对
        } else if (node.getName().equals("URL")) {//url可能为空的
            hashMap.put("URL", node.getText());//这是下载地址，到时候比对的是url，这里还没有分割
            System.out.println("xml的所有url的hashmap集合数量" + hashMapListtemp.size());
            hashMapListtemp.add(hashMap);
        }


        //同时迭代当前节点下面的所有子节点  
        //使用递归  
        Iterator<Element> iterator = node.elementIterator();
        while (iterator.hasNext()) {
            Element e = iterator.next();
            listnodes(e);
        }
    }

    /**
     *  
     *      * 获取当前时间 
     *      *  
     *      * @return 
     *      
     */
    public String getCurrentTime_Today() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        return sdf.format(new java.util.Date());
    }

    private void showProgressDialog01() {
        mMProgressDialog = new MProgressDialog.Builder(this)
                .isCanceledOnTouchOutside(true)
                .setOnDialogDismissListener(new MProgressDialog.OnDialogDismissListener() {
                    @Override
                    public void dismiss() {
                        //mHandler.removeCallbacksAndMessages(null);
                    }
                })
                .build();
        mMProgressDialog.show("复制中...");
    }

    public static int reboot() {
        int r = 0;
        try {
            Process process = Runtime.getRuntime().exec("su -c reboot");
            r = process.waitFor();

        } catch (IOException e) {
            e.printStackTrace();
            r = -1;
        } catch (InterruptedException e) {
            e.printStackTrace();
            r = -1;
        }
        Log.i("info", "time: " + r);
        return r;
    }


    public String download(final String urlstr) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    // 创建一个URL对象
                    url = new URL(urlstr);
                    // 创建一个Http连接
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    String string = urlConn.getInputStream().toString();
                    urlConn.setRequestMethod("GET");
                    urlConn.setConnectTimeout(8000);
                    urlConn.setReadTimeout(8000);
                    // 使用IO流读取数据 ,防止中文出现乱码 gb2312
                    buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
                    while ((line = buffer.readLine()) != null) {
                        sb.append(line);
                    }
                    System.out.println(sb.toString() + "aaaaaaaaaaaaaaaaaaaa");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        buffer.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return sb.toString();
    }

    public String[] split(String string) {
        String[] temp = null;
        temp = string.split(";");
        return temp;
    }

    // 视频请求
    public void VideoDownloadAPI(String videourl, final ProgressBar myprogress) {
        final String savePath = getExternalStorageDirectory().toString() + "/"
                + "guoguang/video/ee.mp4";
        HttpCallBack call = new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                // 更新进度条进度
                handler.postDelayed(runnable1, 500);//下载时间
               /* try {
                    Thread.sleep(1000);
                    //Thread.interrupted();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                myprogress.setMax((int) count);
                myprogress.setProgress((int) current);
            }

            @Override
            public void onSuccess(byte[] t) {
                super.onSuccess(t);
                handler.removeCallbacks(runnable1);
                handler2.removeCallbacks(runnable2);
                http.cleanCache();
                ViewInject.toast(MainActivity.this, "下载完了，是否还会走这");//测试是还会走这的
                myim.setImageBitmap(getBitmap(savePath));
                myim.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if (savePath.equals("")) {
                            ViewInject.toast("无视频");
                        } else {
                            Intent intents = new Intent(Intent.ACTION_VIEW);
                            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intents.setDataAndType(Uri.fromFile(new File(savePath)), "video/*");
                            startActivity(intents);
                        }
                    }
                });
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                // 提示失败
                // ViewInject.toast(context,
                // context.getString(R.string.internet_error));
            }
        };

        try {
            videourl = URLEncoder.encode(videourl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        videourl = videourl.replace("%3A", ":");
        videourl = videourl.replace("%2F", "/");
        // 配置网络请求cache参数UTF-8

        http.download(savePath, videourl, call);
        //http.cancel(url);

    }

    public void initnet() {
        http = new KJHttp();
        httpconfig = new HttpConfig();
        httpconfig.cacheTime = 0;
        HttpConfig.TIMEOUT = 20000;
        http.setConfig(httpconfig);
    }


    //下载视频和图片资源数据
    public void download(final ProgressBar progressBar, String videourl) {
        final String savePath = getExternalStorageDirectory().toString() + "/"
                + "guoguang/video/ee.mp4";
        HttpCallBack call = new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                // 更新进度条进度
                progressBar.setMax((int) count);
                progressBar.setProgress((int) current);
            }

            @Override
            public void onSuccess(byte[] t) {
                super.onSuccess(t);

            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);

            }
        };
        http = new KJHttp();
        HttpConfig httpconfig = new HttpConfig();
        try {
            videourl = URLEncoder.encode(videourl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        videourl = videourl.replace("%3A", ":");
        videourl = videourl.replace("%2F", "/");
        // 配置网络请求cache参数UTF-8
        httpconfig.cacheTime = 0;
        HttpConfig.TIMEOUT = 20000;
        http.setConfig(httpconfig);
        http.download(savePath, videourl, call);
    }

    /**
     * 获得视频的缩略图
     */
    public Bitmap getBitmap(String imgPath) {
        // 获取第一个关键帧
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        if (getAndroidSDKVersion() >= 10) {
            // retriever.setDataSource(imgPath);
            // Bitmap bmp = retriever.getFrameAtTime(0,
            // MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
            Bitmap bp = ThumbnailUtils.createVideoThumbnail(imgPath, Thumbnails.MINI_KIND);
            return bp;
        } else {
            return null;
        }
    }

    /**
     * 当前系统的版本号
     */
    public int getAndroidSDKVersion() {
        int version;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            System.out.println(e.toString());
            return -1;
        }
        return version;
    }

    private class mytask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            StringBuffer sb = new StringBuffer();
            String line = null;
            BufferedReader buffer = null;
            try {
                url = new URL(params[0]);
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                String string = urlConn.getInputStream().toString();
                urlConn.setRequestMethod("GET");
                urlConn.setConnectTimeout(8000);
                urlConn.setReadTimeout(8000);
                buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
                while ((line = buffer.readLine()) != null) {
                    sb.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    buffer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return sb.toString();
        }

        // doInBackground()返回调用，返回值也是从doback里面传来的
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            ascontent = result;
            System.out.println("jieyasuo+xml:" + ascontent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(mseeagebean mseeagebean) {
        Toast.makeText(this, "sas", Toast.LENGTH_SHORT).show();
        eventbus.setText(mseeagebean.getString());
    }

    private String time() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        Date currentdate = new Date(System.currentTimeMillis());
        String timeString = simpleDateFormat.format(currentdate);
        return timeString;
    }

    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /*获取设备UUID<uses-permission android.permission.READ_PHONE_STATE/>*/
    private String getMyUUID() {
        final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();
        return uniqueId;
    }
}
